package cn.iocoder.yudao.module.picturebook.service.plan;

import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.service.book.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.picturebook.controller.admin.plan.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.plan.PlanDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.plan.PlanMapper;

/**
 * 每日任务表	 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class PlanServiceImpl implements PlanService {

    @Resource
    private PlanMapper planMapper;
    @Resource
    private BookService bookService;

    // ... existing code ...
    @Override
    public Integer createPlan(PlanSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            return null;
        }

        // 插入
        PlanDO plan = BeanUtils.toBean(createReqVO, PlanDO.class);
        planMapper.insert(plan);

        // 添加空值检查
        if (plan.getPlanId() == null) {
            return null;
        }

        // 返回
        return plan.getPlanId();
    }

    @Override
    public void updatePlan(PlanSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            return;
        }
        if (updateReqVO.getPlanId() == null) {
            return;
        }

        // 校验存在
        if (planMapper.selectById(updateReqVO.getPlanId()) == null) {
            return;
        }
        // 更新
        PlanDO updateObj = BeanUtils.toBean(updateReqVO, PlanDO.class);
        planMapper.updateById(updateObj);
    }

    @Override
    public void deletePlan(Integer id) {
        // 参数校验
        if (id == null) {
            return;
        }

        // 校验存在
        if (planMapper.selectById(id) == null) {
            return;
        }
        // 删除
        planMapper.deleteById(id);
    }

    @Override
    public void deletePlanListByIds(List<Integer> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 删除
        planMapper.deleteByIds(ids);
    }


    private void validatePlanExists(Integer id) {
        // 参数校验
        if (id == null) {
            return;
        }

        if (planMapper.selectById(id) == null) {
            log.error("[getPlan][id({}) 不存在]", id);
            // 不抛出异常，仅记录日志
            return;
        }
    }

    @Override
    public PlanDO getPlan(Integer id) {
        // 参数校验
        if (id == null) {
            return null;
        }

        return planMapper.selectById(id);
    }

    @Override
    public PageResult<PlanDO> getPlanPage(PlanPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            return PageResult.empty();
        }

        return planMapper.selectPage(pageReqVO);
    }

    @Override
    public List<BookDO> getPlanByBigPlanIdAndTime(Integer bigPlanId, LocalDate now) {
        // 参数校验
        if (bigPlanId == null || now == null) {
            return Collections.emptyList();
        }

        try {
            PlanDO plan = planMapper.getPlanByBigPlanIdAndTime(bigPlanId, now);
            if (plan == null) {
                return new ArrayList<>();
            }

            String planBookStr = plan.getPlanBook();
            if (planBookStr == null || planBookStr.trim().isEmpty()) {
                return new ArrayList<>();
            }

            // 1. 校验并清洗字符串
            String cleaned = planBookStr.replaceAll("[^0-9,]", "");
            // 2. 校验格式是否为逗号分隔的整数列表
            if (!cleaned.matches("(\\d+,)*\\d+")) {
                return new ArrayList<>();
            }

            List<Integer> planBook = Arrays.stream(cleaned.split(","))
                    .filter(s -> !s.isEmpty())
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());

            if (planBook.isEmpty()) {
                return new ArrayList<>();
            }

            // 3. 使用批量查询代替循环单次查询（需确保 bookService 有 selectByIds 方法）
            List<BookDO> bookList = bookService.selectByIds(planBook.stream()
                    .map(Long::valueOf)
                    .collect(Collectors.toList()));

            // 过滤掉 null 值（根据业务需求可选）
            return bookList.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            // 出现异常时返回空列表
            return Collections.emptyList();
        }
    }


    @Override
    public List<List<BookDO>> getPlanByBigPlanId(Integer id) {
        // 参数校验
        if (id == null) {
            return Collections.emptyList();
        }

        try {
            List<PlanDO> planList = planMapper.getPlanByBigPlanId(id);
            if (planList == null) {
                return Collections.emptyList();
            }

            List<List<BookDO>> bookList = new ArrayList<>();
            for (PlanDO plan : planList) {
                if (plan == null) {
                    continue;
                }

                //根据当天计划中的书籍id获取书籍 信息
                String planBookStr = plan.getPlanBook();
                if (planBookStr == null || planBookStr.isEmpty()) {
                    bookList.add(Collections.emptyList());
                    continue;
                }

                try {
                    // 1. 去除所有非数字和逗号的字符（如 [ ] 空格）
                    String cleaned = planBookStr.replaceAll("[^0-9,]", ""); // 结果为 "1001,1002"
                    // 2. 按逗号拆分并转换为整数
                    List<Integer> planBook = Arrays.stream(cleaned.split(","))
                            .filter(s -> !s.isEmpty()) // 避免空字符串
                            .map(Integer::parseInt)
                            .collect(Collectors.toList());
                    List<BookDO> bookList2 = new ArrayList<>(); // 重命名为 bookList2 以避免命名冲突
                    //根据书籍id查询书籍
                    for (Integer bookId : planBook) {
                        if (bookId != null) {
                            BookDO book = bookService.selectById(Long.valueOf(bookId));
                            bookList2.add(book);
                        }
                    }
                    bookList.add(bookList2);
                } catch (Exception e) {
                    // 解析书籍ID失败时添加空列表
                    bookList.add(Collections.emptyList());
                }
            }
            return bookList;
        } catch (Exception e) {
            // 出现异常时返回空列表
            return Collections.emptyList();
        }
    }

    @Override
    public void deletePlanByBigPlanId(Integer id) {
        // 参数校验
        if (id == null) {
            return;
        }

        planMapper.deletePlanByBigPlanId(id);
    }
// ... existing code ...

}